package middleware

import (
	"context"
	"sale-admin/config/redis"
	"sale-admin/internal/define"
	"time"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
)

func LoginHandle() gin.HandlerFunc {
	return func(c *gin.Context) {
		authorizationToken := c.GetHeader("Authorization")
		if authorizationToken == "" {
			if authorizationToken = c.Query("Authorization"); authorizationToken == "" {
				response.JSON(c, nil, errorx.New("请重新登录", 100001))
				c.Abort()
				return
			}
		}
		// redis超时控制
		ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
		defer cancel()
		exists, _ := redis.NewDB().HExists(ctx, define.RedisUserLoginTokenPrefix+authorizationToken, "user_id").Result()
		if !exists {
			response.JSON(c, nil, errorx.New("请重新登录", 100001))
			c.Abort()
			return
		}
		// token延长有效期
		redis.NewDB().Expire(ctx, define.RedisUserLoginTokenPrefix+authorizationToken, time.Hour*2)
		c.Next()
	}
}
